Divide Two Integers

Divide two integers without using multiplication, division and mod operator.

If it is overflow, return MAX_INT.

Solution:

  1. public class Solution {
  2. public int divide(int dividend, int divisor) {
  3. if (dividend == Integer.MIN_VALUE && divisor == -1) {
  4. return Integer.MAX_VALUE;
  5. }
  6. long p = Math.abs((long)dividend);
  7. long q = Math.abs((long)divisor);
  8. int res = 0;
  9. while (p >= q) {
  10. int count = 0;
  11. while (p >= (q << count)) {
  12. count++;
  13. }
  14. p -= q << (count - 1);
  15. res += 1 << (count - 1);
  16. }
  17. return ((dividend^divisor) >>> 31 == 0) ? res : -res;
  18. }
  19. }